const b = require('/usr/local/lib/node_modules/bonescript'); //bonescript
const EventEmitter = require('events').EventEmitter;


/**
 * CONSTANTS
 */
const CheckInterval = 1000;
const DC_POWER_PIN = 'P9_16';
const BUZZER_PIN = 'P9_25';
const LID_PIN = 'P9_27';

const COLLECTOR_PIN = 'P8_4';
const MQTT_PIN = 'P8_5';
/**
 * the class monitor hardware GPIO pin, such as AC power on/off,
 * and lid status(open ,close).
 * It will trigger events based on the monitoring GPIO status
 */
class Monitor extends EventEmitter {

  constructor(logger, msgClient) {
    super();
    this._logger = logger;
    this._msgClient = msgClient;
    this._dc_power_on = 0; // 0 mans DC off, 1 means DC on
    this._lid_closed = 0; // 0 means close, 1 means open

    b.pinMode(DC_POWER_PIN, b.INPUT);
    b.pinMode(LID_PIN, b.INPUT);
    b.pinMode(BUZZER_PIN, b.OUTPUT, 7, 'pulldown');
    b.pinMode(COLLECTOR_PIN, b.OUTPUT, 7, 'pulldown');
    b.pinMode(MQTT_PIN, b.OUTPUT, 7, 'pulldown');

    setInterval(() => this.check(), CheckInterval);
  }


  // /////////////////////////////////////////////////////////
  // Private methods
  // /////////////////////////////////////////////////////////

  // log info message and pass info message to msgClient if
  // it exists
  info(msg) {
    this._logger.info(msg);
    this._msgClient.send(msg);
  }

  // log error message and pass error message to msgClient if
  // it exists
  error(msg) {
    this._logger.error(msg);
    this._msgClient.send(msg);
  }

  check() {
    this.checkDcPower();
    this.checkDoorStatus();
  }

  checkDcPower() {
    b.digitalRead(DC_POWER_PIN, (x) => {
      if (x.err) return;
      if (this._dc_power_on !== x.value) {
        this.info(`DC Power changed. value: ${x.value}`);

        this.emit('power', x.value === 1);
      }
      this._dc_power_on = x.value;
    });
  }

  checkDoorStatus() {
    b.digitalRead(LID_PIN, (x) => {
      if (x.err) return;
      if (this._lid_closed !== x.value) {
        this.info(`Lid Status changed. value: ${x.value}`);
        // b.digitalWrite(BUZZER_PIN, x.value);
        if (x.value === 1) {
          this.turnOnBuzzer();
        } else {
          this.turnOffBuzzer();
        }
        this.emit('lid', x.value === 1);
      }
      this._lid_closed = x.value;
    });
  }

  turnOnBuzzer() {
    let value = 0;
    this._buzzerInterval = setInterval(() => {
      value = (value + 1) % 2;
      console.log(value);
      b.digitalWrite(BUZZER_PIN, value);
    }, 1000);
  }

  turnOffBuzzer() {
    clearInterval(this._buzzerInterval);
    b.digitalWrite(BUZZER_PIN, 0);
  }

  blinkLed(pin_num) {
    b.digitalWrite(pin_num, 1);
    setTimeout(() => b.digitalWrite(pin_num, 0), 500);
  }

  blinkCollector() {
    this.blinkLed(COLLECTOR_PIN);
  }

  blinkMqtt() {
    this.blinkLed(MQTT_PIN);
  }
}



module.exports = Monitor;
